//
//  PriceViewModel.m
//  
//
//  Created by ツナミ 龍 on 15/12/16.
//
//

#import "PriceViewModel.h"
#import "CheckResultUserDefaults.h"
#import "UIDevice+IdentifierAddition.h"

@interface NSString (Convert)

- (NSString *)pureLineFeed;

@end

@implementation  NSString (Convert)

- (NSString *)pureLineFeed
{
    NSString *line = [self stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];
    return line;
}

@end

@implementation PriceViewModel

+ (instancetype)sharedInstance
{
    static dispatch_once_t onceToken;
    static PriceViewModel *_instance = nil;
    dispatch_once(&onceToken, ^{
        _instance = [[[self class] alloc] init];
    });
    return _instance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initialize];
    }
    return self;
}

- (AuthLoginService *)service
{
    if (_service == nil) {
        _service = [[AuthLoginService alloc] init];
    }
    return _service;
}

- (void)initialize
{
    self.executeSend = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
                            return  [self executePriceSignal];
                        }];
    
    self.connectionErrors = self.executeSend.errors;
}

- (RACSignal *)executePriceSignal
{
    UIDevice *dev = [UIDevice currentDevice];
    CheckResultUserDefaults *defaults = [CheckResultUserDefaults standardUserDefaults];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    params[KEY_AUTHID] = defaults.authCode;
    params[KEY_CAREER] = dev.carrierName;
    params[KEY_MAKER] = @"APPLE";
    params[KEY_MODEL] = dev.model;
    params[KEY_MODEL_NAME] = dev.machineShortName;
    params[KEY_VOLUME] = DEVICE_TOTAL_VOLUME;
    params[KEY_DIAGNOSTICS_RESULT] = [CheckResultUserDefaults diagnosisResultAPIString];
    
//    NSString *File = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
//    NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithContentsOfFile:File];
//    params[KEY_VERSION] = [dict objectForKey:@"App version"];
    
    return [[self.service sendPriceSignal:params]
            doNext:^(NSDictionary *result) {
                // results;
                
                self.message1String = [[result objectForKey:RESP_KEY_MESSAGE1] pureLineFeed];
                self.message2String = [[result objectForKey:RESP_KEY_MESSAGE2] pureLineFeed];
                self.message3String = [[result objectForKey:RESP_KEY_MESSAGE3] pureLineFeed];
                
                self.apiSucceed = YES; // must be last
            }];
}

@end
